package com.xueshandai.db.migration.tool;

import com.xueshandai.db.migration.mode.config.TableMap;
import org.apache.log4j.Logger;


import java.io.*;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by dengzt on 2015/1/6.
 */
public class TableMapUtil {

    static Logger logger = Logger.getLogger(FileUtil.class.toString());

    private List<TableMap> tableMapList;

    private static TableMapUtil tableMapUtil;

    private TableMapUtil() {
        this.tableMapList = new LinkedList<TableMap>();
        List<File> fileList = FileUtil.getFileListInConfDirInUserDir();
        for (File file : fileList) {
            try {
                FileReader fileReader = new FileReader(file);
                BufferedReader bufferedReader = new BufferedReader(fileReader);
                String jsonStr = bufferedReader.readLine();
                while ( jsonStr != null ) {
                    TableMap tableMap = TableMap.parse(jsonStr);
                    tableMapList.add(tableMap);

                    jsonStr = bufferedReader.readLine();
                }
            } catch (FileNotFoundException e) {
                logger.error(e);
            } catch (IOException e) {
                logger.error(e);
            }
        }
        logger.info("表字段映射初始化成功，共加载了"+tableMapList.size()+"张表的字段映射配置文件");
    }

    private synchronized static void init() {
        if ( tableMapUtil == null ) {
            tableMapUtil = new TableMapUtil();
        }
    }

    public static TableMapUtil getInstance() {
        if ( tableMapUtil == null ) {
            init();
        }
        return tableMapUtil;
    }

    public List<TableMap> getTableMapList() {
        return tableMapList;
    }
}
